//
//  HealthKnowledgeDetailViewController.m
//  LoveHealth
//
//  Created by 枫哥 on 14-9-18.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "HealthKnowledgeDetailViewController.h"
#import "HealthKnowledgeDetailView.h"
#import "SQLHelper.h"
#import "HealthKnowledgeDetail.h"

#import "UIImageView+WebCache.h"

#import "SphereMenu.h"
#import "UMSocial.h"

#import "NetHelper.h"

#import "MONActivityIndicatorView.h"
#import "KGStatusBar.h"
@interface HealthKnowledgeDetailViewController ()<SphereMenuDelegate,UMSocialUIDelegate,MONActivityIndicatorViewDelegate>

@property (nonatomic,retain) HealthKnowledgeDetailView * detailView;
@property (nonatomic,retain) HealthKnowledgeDetail * knowledgeDeatail;
@property (nonatomic,retain) HealthKnowledgeDetail * detail;
@property (nonatomic,retain)NSNumber * KnowledgeID;
@property (nonatomic,retain)UIImage * showImage;

//声明一个loading用于加载未完成时
@property (nonatomic,retain)MONActivityIndicatorView  * indicatorView;
@end

@implementation HealthKnowledgeDetailViewController
- (void)dealloc
{
    self.indicatorView = nil;
    
    self.favoriteDetail = nil;
    //self.knowledgeDeatail = nil;
    self.detailView = nil;
    self.knowledgeList = nil;
    
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)loadView
{
    _detailView = [[HealthKnowledgeDetailView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.detailView;
    
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    //判断是否是从收藏列表进来的
    if (self.favoriteDetail != nil) {
        self.detailView.knowledgeDetail = self.favoriteDetail;
    }else{
        [self setupActivityIndicator];
        //判断是从主页列表还是搜索列表进来的
        if (self.searchResult != nil) {
            self.KnowledgeID = self.searchResult.ID;
            NSString * url = APIImageURL(self.searchResult.img)
            [self.detailView.detailImageView sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                self.showImage = image;
            }];
            //        [self.detailView.detailImageView setImageWithURL:[NSURL URLWithString:url] success:^(UIImage *image, BOOL cached) {
            //            self.showImage = image;
            //        } failure:nil];
            
        }else{
            self.KnowledgeID = self.knowledgeList.ID;
            self.showImage = self.knowledgeList.showImage;
        }
        
        
        
        [self p_sendReuqest];
        self.detailView.detailImageView.image = self.showImage;
        
        //    UIBarButtonItem * collectionBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(didClickCollectionButtonItemAction:)];
        //    self.navigationItem.rightBarButtonItem = collectionBarButtonItem;
        //    [collectionBarButtonItem release];
        

    }
    
    
}

#pragma mark--------------loading----------------------
//设置loading
- (void)setupActivityIndicator
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.delegate = self; //设置代理
    _indicatorView.numberOfCircles = 6; //圆圈个数
    _indicatorView.radius = 10;//圆圈大小
    _indicatorView.internalSpacing = 3;//圆圈之间的间距
    _indicatorView.center = self.view.center;
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}
//指示器 代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    CGFloat red   = (arc4random() % 256)/255.0;
    CGFloat green = (arc4random() % 256)/255.0;
    CGFloat blue  = (arc4random() % 256)/255.0;
    CGFloat alpha = 1.0f;
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

//弹出菜单
- (void)setupSphereMenu
{
    
    UIImage *startImage = [UIImage imageNamed:@"more_img"];
    UIImage *image1 = [UIImage imageNamed:@"favorite_img"];
    UIImage *image2 = [UIImage imageNamed:@"share_img"];
    NSArray *images = @[image1, image2];
    SphereMenu *sphereMenu = [[SphereMenu alloc] initWithStartPoint:CGPointMake(self.view.bounds.size.width-30, self.view.bounds.size.height-45)
                                                         startImage:startImage
                                                      submenuImages:images];
    sphereMenu.delegate = self;
    [self.view addSubview:sphereMenu];
    
}


- (void)sphereDidSelected:(int)index
{
    NSLog(@"sphere %d selected", index);
    //收藏
    if (index == 0) {
        NSLog(@"sss = %@",_knowledgeDeatail);
        NSLog(@"%@",_knowledgeList.ID);
        SQLHelper * database = [SQLHelper shareInstance];
        BOOL result = [database existWithID:[_knowledgeList.ID integerValue] tableName:KknowledgeTableName];
        if (result == NO) {
            [database insertWithValue:_knowledgeDeatail tableName:KknowledgeTableName];
            NSLog(@"收藏成功");
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [alert show];
            [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:1];
            //[alert release];
        }else{
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过了" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [alert show];
            [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:0.5];
            //[alert release];
        }
        
    }
    if (index == 1) {
        
        NSString *shareText = [NSString stringWithFormat:@"我在<<爱健康>>看到了一条新闻:%@...........爱生活，爱健康",self.knowledgeDeatail.title];             //分享内嵌文字
        UIImage *shareImage = self.knowledgeDeatail.showImage;          //分享内嵌图片
        
        //如果得到分享完成回调，需要设置delegate为self
        [UMSocialSnsService presentSnsIconSheetView:self appKey:UmengAppkey shareText:shareText shareImage:shareImage shareToSnsNames:@[UMShareToSina,UMShareToWechatTimeline,UMShareToWechatSession,UMShareToWechatFavorite,UMShareToQzone,UMShareToQQ,UMShareToEmail,UMShareToSms] delegate:self];
        
    }


}
- (void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
    
}


- (void)dismissAlert:(UIAlertView *)alert
{
    if (alert) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        [alert release];
    }
}


- (void)p_sendReuqest
{
    
    //拼接网址
    NSString * urlString =[[NSString alloc]initWithFormat:@"%@?id=%@",APIHealthKnowledgeDetail,self.KnowledgeID];
    
    //NSURL * url = [NSURL URLWithString:urlString];
    
    
    //建立网络连接
    __block  HealthKnowledgeDetailViewController * knowledgeListDVC = self;
    
    [[NetHelper shareInstance]loadingDataWithUrlString:urlString urlExpireInSeconds:30 download:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        if (data != nil && connectionError == nil) {
            //解析数据
            NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            //数据处理
            NSDictionary * detailDic = sourceDic[@"yi18"];
            
            _detail = [[HealthKnowledgeDetail alloc]init];
            [_detail setValuesForKeysWithDictionary:detailDic];
            _detail.showImage = knowledgeListDVC.showImage;
            knowledgeListDVC.knowledgeDeatail = _detail;
            [_detail release];
            knowledgeListDVC.detailView.knowledgeDetail = knowledgeListDVC.knowledgeDeatail;
            

        }else{
            [KGStatusBar showErrorWithStatus:kNetErrorMessage];
        }
        
        [knowledgeListDVC setupSphereMenu];

        [knowledgeListDVC.indicatorView stopAnimating];

    }];
    
    /*[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        //解析数据
        NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        //数据处理
        NSDictionary * detailDic = sourceDic[@"yi18"];
        
        _detail = [[HealthKnowledgeDetail alloc]init];
        [_detail setValuesForKeysWithDictionary:detailDic];
        _detail.showImage = knowledgeListDVC.showImage;
        knowledgeListDVC.knowledgeDeatail = _detail;
        [_detail release];
        knowledgeListDVC.detailView.knowledgeDetail = knowledgeListDVC.knowledgeDeatail;
    }];*/
    
}


//- (void)didClickCollectionButtonItemAction:(UIBarButtonItem *)barButton
//{
//    /*
//     //用FMDB将数据存入数据库(documentory目录下  叫favorite)
//     
//     NSLog(@"data = %@",NSHomeDirectory());
//     NSString * documentory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//     NSString * path = [documentory stringByAppendingPathComponent:@"favorite.sqlite"];
//     //创建数据库
//     FMDatabase * db = [FMDatabase databaseWithPath:path];
//     [db open];
//     if (![db open]) {
//     NSLog(@"Open database failed");
//     return;
//     }
//     //是否有News表 如果没有表
//     if (NO == [self isTableOK:@"News" database:db]){
//     //创建News表
//     [db executeUpdate:@"CREATE TABLE News (id INTEGER PRIMARY KEY NOT NULL UNIQUE, title TEXT NOT NULL, message TEXT, data BLOB)"];
//     //插入数据
//     [self insertDataToDB:db];
//     [db close];
//     }else{
//     //有这个News表
//     FMResultSet * set = [db executeQuery:@"SELECT id FROM News WHERE title = ?",_news.title];
//     if ([set next]){
//     //有表有数据  提示 已经收藏过了
//     UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//     [alert show];
//     [alert release];
//     }else{
//     //有表没这个数据
//     [self insertDataToDB:db];
//     [db close];
//     }
//     }
//     */
//    NSLog(@"sss = %@",_knowledgeDeatail);
//    NSLog(@"%@",_knowledgeList.ID);
//    SQLHelper * database = [SQLHelper shareInstance];
//    BOOL result = [database existWithID:[_knowledgeList.ID integerValue] tableName:KknowledgeTableName];
//    if (result == NO) {
//        [database insertWithValue:_knowledgeDeatail tableName:KknowledgeTableName];
//        NSLog(@"收藏成功");
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }else{
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
//    
//    
//}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
